package com.xyy.saas.payment.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.adapter.channel.fm.config.BankConfigManager;
import com.xyy.saas.payment.dao.model.ApplyOpenAccountStatus;
import com.xyy.saas.payment.enums.Depart;
import com.xyy.saas.payment.exception.PaymentException;
import com.xyy.saas.payment.manage.cores.vo.ResultVO;
import com.xyy.saas.payment.pojo.domain.QueryMerchantDayBalanceDO;
import com.xyy.saas.payment.pojo.vo.DictEntity;
import com.xyy.saas.payment.pojo.vo.QueryFuminRecordVo;
import com.xyy.saas.payment.service.ApplyOpenAccountStatusService;
import com.xyy.saas.payment.service.OpenAccountService;
import com.xyy.saas.payment.service.job.SyncFuminDataService;
import com.xyy.saas.payment.service.report.QueryFuminService;
import com.xyy.saas.payment.util.JSONUtils;
import com.xyy.saas.payment.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 公共信息接口
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private QueryFuminService queryFuminService;
    @Autowired
    private ApplyOpenAccountStatusService applyOpenAccountStatusService;
    @Autowired
    private OpenAccountService openAccountService;
    @Autowired
    private SyncFuminDataService syncFuminDataService;
    @Autowired
    private BankConfigManager bankConfigManager;

    /** 获取部门信息 */
    @GetMapping(value = "/getDepart",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getDepart(){
        JSONArray ja = new JSONArray();
        for (Depart depart:Depart.values()) {
            JSONObject jo = new JSONObject();
            jo.put("key",depart.getCode());
            jo.put("value",depart.getDesc());
            ja.add(jo);
        }
        return ja.toJSONString();
    }

    /** 获取字典 */
    @GetMapping(value = "/getDict/{name}")
    public ResultVO getDict(@PathVariable("name") String name){
        List<DictEntity> list = new ArrayList<>();
        try {
            Map<String, String> bean = SpringUtils.getBean(name, Map.class);
            for(Map.Entry<String, String> entry : bean.entrySet()){
                DictEntity entity = new DictEntity();
                entity.setKey(entry.getKey());
                entity.setValue(entry.getKey());
                entity.setLabel(entry.getValue());
                list.add(entity);
            }
        } catch (Exception e) {
            return ResultVO.createError("no dictionary.");
        }
        return ResultVO.createSuccess(list);
    }

    /** 获取字典 */
    @GetMapping(value = "/getDict/{name}/{type}")
    public ResultVO getDict(@PathVariable("name") String name, @PathVariable(value = "type") String type){
        List<DictEntity> list = new ArrayList<>();
        try {
            if("map".equals(type)) {
                Map<String, String> bean = SpringUtils.getBean(name, Map.class);
                for(Map.Entry<String, String> entry : bean.entrySet()){
                    DictEntity entity = new DictEntity();
                    entity.setKey(entry.getKey());
                    entity.setValue(entry.getKey());
                    entity.setLabel(entry.getValue());
                    list.add(entity);
                }
            }else if ("list".equals(type)) {
                list = SpringUtils.getBean(name, List.class);
            } else {
                return ResultVO.createError("no dictionary.");
            }

        } catch (Exception e) {
            return ResultVO.createError("no dictionary.");
        }
        return ResultVO.createSuccess(list);
    }

    /** 查询富民账户明细 */
    @RequestMapping(value = "/queryFuminRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResultVO queryFuminRecord(@RequestBody QueryFuminRecordVo queryFuminRecordVo) {
        try {
            return ResultVO.createSuccess(queryFuminService.queryFuminRecord(queryFuminRecordVo));
        } catch (PaymentException e) {
            log.info("CommonController#queryFuminRecord error queryVo:{} e:{}", JSONUtils.toJSON(queryFuminRecordVo), e.getErrCode()+e.getErrMsg());
            return ResultVO.createError(e.getErrMsg());
        }
    }

    @RequestMapping(value = "/queryMerchantDayBalance", method = RequestMethod.POST)
    public ResultVO queryMerchantDayBalance(@RequestBody QueryMerchantDayBalanceDO queryMerchantDayBalanceDO) {
        try {
            return ResultVO.createSuccess(queryFuminService.queryBalanceRecord(queryMerchantDayBalanceDO));
        }
        catch(Exception ex) {
            log.error(ex.getMessage(), ex);
            return ResultVO.createError(ex.getMessage());
        }
    }

    @RequestMapping(value = "/queryMerchantBalance", method = RequestMethod.POST)
    public ResultVO queryMerchantBalance(@RequestBody QueryMerchantDayBalanceDO queryMerchantDayBalanceDO) {
        try {
            return ResultVO.createSuccess(queryFuminService.queryMerchantRecord(queryMerchantDayBalanceDO));
        }
        catch(Exception ex) {
            log.error(ex.getMessage(), ex);
            return ResultVO.createError(ex.getMessage());
        }
    }

    /** 微信开户意愿申请重试 */
    @GetMapping(value = "/retryOpenAccountApplyment")
    public String retryOpenAccountApplyment(@RequestParam(value = "applyCode") String applyCode) {
        log.info("openAccountApplyment start. applyCode:{}", applyCode);
        ApplyOpenAccountStatus applyOpenAccountStatus = applyOpenAccountStatusService.selectByApplyCode(applyCode);
        if(null == applyOpenAccountStatus) {
            return "applyOpenAccountStatus is null.";
        }
        return JSONUtils.toJSON(openAccountService.againOpenAccountApplyment(applyOpenAccountStatus.getApplyCode()));
    }

    /** 同步富民子账户数据 */
    @RequestMapping(value = {"/synFMPayReportByAccountId"}, method = RequestMethod.POST)
    public String synFMPayReportByAccountId(@RequestParam String startTime, @RequestParam String endTime, @RequestBody List<String> accountIds) {
        for (String accountId : accountIds) {
            bankConfigManager.getFuminAccountConfig().forEach(item -> {
                if(item.getAccountId().equals(accountId)) {
                    log.info("TestController#synFMDataByDate syncFuminDataService.synchronizeFuminDataByDay SyncFMPayReportConfigBO:{}", JSONUtils.toJSON(item));
                    syncFuminDataService.synchronizeFuminDataByDay(startTime, endTime, item);
                }
            });
        }
        return "ok.";
    }

}
